﻿using Hangfire;
using Hangfire.MySql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Volo.Abp;
using Volo.Abp.AspNetCore;
using Volo.Abp.BackgroundWorkers.Hangfire;
using Volo.Abp.Data;
using Volo.Abp.Modularity;

namespace Cjj.Exam.Hangfire
{
    [DependsOn((
    //...other dependencies

    typeof(AbpBackgroundWorkersHangfireModule) //Add the new module dependency
    )
        ,
        (typeof(AbpAspNetCoreModule))
        )
        ]
    public class ExamHangfireModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();
            var hostingEnvironment = context.Services.GetHostingEnvironment();

            //... other configarations.

            ConfigureHangfire(context, configuration);
        }


        private void ConfigureHangfire(ServiceConfigurationContext context, IConfiguration configuration)
        {
            context.Services.AddHangfire(config =>
            {
                //config.UseMySqlStorage(configuration.GetConnectionString("Default"));
                config.UseStorage(new MySqlStorage(configuration.GetConnectionString("Default"), new MySqlStorageOptions
                {
                    TransactionIsolationLevel = IsolationLevel.ReadCommitted,//事务隔离级别。默认为已提交读
                    QueuePollInterval = TimeSpan.FromSeconds(15),//作业队列轮询间隔。默认值为 15 秒。
                    JobExpirationCheckInterval = TimeSpan.FromHours(1),//作业过期检查间隔（管理过期记录）。默认值为 1 小时。
                    CountersAggregateInterval = TimeSpan.FromMinutes(5),//聚合计数器的间隔。默认为 5 分钟。
                    PrepareSchemaIfNecessary = true,// 如果设置为true，它会创建数据库表。默认为true。
                    DashboardJobListLimit = 50000,//仪表板作业列表限制。默认值为 50000
                    TransactionTimeout = TimeSpan.FromMinutes(1),//交易超时。默认值为 1 分钟。
                    TablesPrefix = "Hangfire"//数据库中表的前缀。默认为无
                }));
            });


        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();
            var env = context.GetEnvironment();
            // ... others
            app.UseHangfireDashboard("/hangfire"); //启用hangfire面板
            app.UseHangfireServer();

            // 创建定时任务
            RecurringJob.AddOrUpdate<CjjJobSchBackWork>(x => x.Run(), "0 */1 * * * ?");
            RecurringJob.AddOrUpdate<CjjVxJobSchBackWork>(x => x.Run(), "0 */1 * * * ?");

            app.UseConfiguredEndpoints();
        }
    }
}
